<template>
  <div class="publish-item-page">
    <div class="publish-container">
      <h1 class="page-title">{{ isEditMode ? '📝 编辑二手商品' : '📝 发布二手商品' }}</h1>
      
      <div class="publish-form">
        <!-- 图片上传区域 -->
        <div class="form-group image-upload-group">
          <label class="form-label">商品图片 <span class="required">*</span></label>
          <div class="image-upload-area">
            <div v-if="!imagePreview" class="upload-placeholder" @click="triggerFileInput">
              <div class="upload-icon">📷</div>
              <p>点击上传商品图片</p>
              <p class="upload-hint">支持 jpg、png、gif、webp 格式，最大 10MB</p>
            </div>
            
            <div v-else class="image-preview-container">
              <img :src="imagePreview" alt="商品图片" class="image-preview" />
              <div class="image-actions">
                <button @click="triggerFileInput" class="change-image-btn">更换图片</button>
                <button @click="removeImage" class="remove-image-btn">删除图片</button>
              </div>
            </div>
            
            <input 
              type="file" 
              ref="fileInput" 
              accept="image/*" 
              @change="handleImageChange" 
              style="display: none;"
            />
          </div>
          <p v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
            上传进度: {{ uploadProgress }}%
          </p>
        </div>

        <!-- 商品标题 -->
        <div class="form-group">
          <label class="form-label">商品标题 <span class="required">*</span></label>
          <input 
            v-model="formData.title" 
            type="text" 
            placeholder="请输入商品标题（如：九成新MacBook Pro）"
            class="form-input"
            maxlength="50"
          />
          <span class="char-count">{{ formData.title.length }}/50</span>
        </div>

        <!-- 商品描述 -->
        <div class="form-group">
          <label class="form-label">商品描述</label>
          <textarea 
            v-model="formData.description" 
            placeholder="请详细描述商品的状况、购买时间、使用情况等..."
            class="form-textarea"
            rows="5"
            maxlength="500"
          ></textarea>
          <span class="char-count">{{ formData.description.length }}/500</span>
        </div>

        <!-- 商品价格 -->
        <div class="form-group">
          <label class="form-label">商品价格 <span class="required">*</span></label>
          <div class="price-input-wrapper">
            <span class="price-symbol">¥</span>
            <input 
              v-model="formData.price" 
              type="number" 
              placeholder="请输入价格"
              class="form-input price-input"
              step="0.01"
              min="0"
            />
          </div>
        </div>

        <!-- 商品成色 -->
        <div class="form-group">
          <label class="form-label">商品成色</label>
          <select v-model="formData.conditionLevel" class="form-select">
            <option value="">请选择成色</option>
            <option value="全新">全新</option>
            <option value="九成新">九成新</option>
            <option value="八成新">八成新</option>
            <option value="七成新">七成新</option>
            <option value="六成新及以下">六成新及以下</option>
          </select>
        </div>

        <!-- 商品分类 -->
        <div class="form-group">
          <label class="form-label">商品分类</label>
          <select v-model="formData.category" class="form-select">
            <option value="">请选择分类</option>
            <option value="电子产品">电子产品</option>
            <option value="图书教材">图书教材</option>
            <option value="运动器材">运动器材</option>
            <option value="生活用品">生活用品</option>
            <option value="其他">其他</option>
          </select>
        </div>

        <!-- 按钮组 -->
        <div class="form-actions">
          <button @click="handlePublish" class="publish-btn" :disabled="publishing || isLoading || isUploading">
              {{ isEditMode ? (publishing ? '更新中...' : '🔄 更新商品') : (publishing ? '发布中...' : '✅ 发布商品') }}
            </button>
          <button @click="handleReset" class="reset-btn" :disabled="publishing || isLoading">
            🔄 重置表单
          </button>
        </div>

        <!-- 提示信息 -->
        <p v-if="message" :class="['message', messageType]">{{ message }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { publishItem, type PublishItemParams, getItemDetail, updateItem } from '../../api/secondHandItem';
import { uploadItemImage } from '../../api/secondHandItem';

const route = useRoute();
const isEditMode = ref(false);
const itemId = ref<number | null>(null);
const isLoading = ref(false);

const router = useRouter();

const fileInput = ref<HTMLInputElement | null>(null);
const imagePreview = ref('');
const uploadedImageUrl = ref('');
const uploadProgress = ref(0);
const isUploading = ref(false);

const publishing = ref(false);
const message = ref('');
const messageType = ref<'success' | 'error'>('success'); // 明确指定类型并设置默认值

const formData = ref({
  title: '',
  description: '',
  price: '',
  conditionLevel: '',
  category: '',
});

// 定时器引用
let messageTimeout: number | null = null;

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click();
};

// 处理图片选择
const handleImageChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    message.value = '请选择图片文件';
    messageType.value = 'error';
    return;
  }
  
  // 验证文件大小（10MB）
  if (file.size > 10 * 1024 * 1024) {
    message.value = '图片大小不能超过10MB';
    messageType.value = 'error';
    return;
  }
  
  // 预览图片
  const reader = new FileReader();
  reader.onload = (e) => {
    imagePreview.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);
  
  // 上传图片
  try {
    uploadProgress.value = 10;
    message.value = '上传中...';
    messageType.value = 'success';
    
    const userId = localStorage.getItem('userId');
    if (!userId) {
      message.value = '未登录，请先登录';
      messageType.value = 'error';
      return;
    }
    
    uploadProgress.value = 50;
    const res = await uploadItemImage(file, Number(userId));
    
    if (res.success && res.data?.url) {
      uploadedImageUrl.value = res.data.url;
      uploadProgress.value = 100;
      message.value = '图片上传成功！';
      messageType.value = 'success';
      
      // 清理之前的定时器
      if (messageTimeout) {
        clearTimeout(messageTimeout);
      }
      
      messageTimeout = window.setTimeout(() => {
        uploadProgress.value = 0;
        message.value = '';
      }, 2000);
    } else {
      message.value = res.message || '上传失败';
      messageType.value = 'error';
      uploadProgress.value = 0;
    }
  } catch (error: any) {
    console.error('上传图片失败:', error);
    message.value = error.message || '上传失败，请稍后重试';
    messageType.value = 'error';
    uploadProgress.value = 0;
  }
};

// 删除图片
const removeImage = () => {
  imagePreview.value = '';
  uploadedImageUrl.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

// 发布商品函数在下面定义，包含编辑模式支持

// 重置表单
const handleReset = () => {
  formData.value = {
    title: '',
    description: '',
    price: '',
    conditionLevel: '',
    category: '',
  };
  removeImage();
  message.value = '';
  
  // 清理定时器
  if (messageTimeout) {
    clearTimeout(messageTimeout);
  }
};

// 加载商品详情
const loadItemDetail = async (id: number) => {
  try {
    isLoading.value = true;
    // 调用getItemDetail API获取商品详情
    const response = await getItemDetail(id);
    
    if (response.success && response.data) {
      const item = response.data;
      formData.value.title = item.title || '';
      formData.value.description = item.description || '';
      formData.value.price = item.price?.toString() || '';
      formData.value.conditionLevel = item.conditionLevel || '';
      formData.value.category = item.category || '';
      // 处理图片 - 接口返回string类型，但为了兼容性也支持数组
      uploadedImageUrl.value = Array.isArray(item.images) && item.images.length > 0 ? item.images[0] : (item.images || '');
      message.value = '编辑模式 - 请更新商品信息';
      messageType.value = 'success';
      isLoading.value = false; // 成功后重置loading状态
    } else {
      throw new Error(response.message || '获取商品详情失败');
    }
  } catch (error: any) {
    message.value = error.message || '获取商品详情失败';
    messageType.value = 'error';
    // 如果获取失败，返回我的发布页面
    router.push('/shop/my-items');
  } finally {
    isLoading.value = false;
  }
};

// 发布商品
const handlePublish = async () => {
  // 表单验证
  // 重置之前的消息
  message.value = '';
  
  if (!formData.value.title.trim()) {
    message.value = '请输入商品标题';
    messageType.value = 'error';
    return;
  }
  
  if (!formData.value.price || Number(formData.value.price) <= 0) {
    message.value = '请输入正确的商品价格';
    messageType.value = 'error';
    return;
  }
  
  if (!uploadedImageUrl.value) {
    message.value = '请上传商品图片';
    messageType.value = 'error';
    return;
  }
  
  const userId = localStorage.getItem('userId');
  if (!userId) {
    message.value = '未登录，请先登录';
    messageType.value = 'error';
    router.push('/login');
    return;
  }
  
  publishing.value = true;
  message.value = '';
  
  try {
    let res;
    if (isEditMode.value && itemId.value) {
      // 调用updateItem API更新商品
      res = await updateItem(itemId.value, {
        title: formData.value.title.trim(),
        description: formData.value.description.trim(),
        price: Number(formData.value.price),
        conditionLevel: formData.value.conditionLevel,
        category: formData.value.category,
        images: uploadedImageUrl.value // API接口期望string类型
      });
      
      if (res.success) {
        message.value = '商品编辑成功！';
        messageType.value = 'success';
      } else {
        message.value = res.message || '更新失败';
        messageType.value = 'error';
        publishing.value = false;
        return;
      }
    } else {
      // 发布商品 - 注意：API接口定义中price是string类型，images是string类型
      res = await publishItem({
        userId: String(userId), // 转换为字符串类型以匹配接口期望
        title: formData.value.title.trim(),
        description: formData.value.description.trim(),
        price: formData.value.price, // 保持string类型
        conditionLevel: formData.value.conditionLevel,
        category: formData.value.category,
        images: uploadedImageUrl.value // 改为string类型以匹配接口定义
      });
      
      if (res.success) {
        message.value = '商品发布成功！即将跳转到我的发布...';
        messageType.value = 'success';
      } else {
        message.value = res.message || '发布失败';
        messageType.value = 'error';
        publishing.value = false;
        return;
      }
    }
    
    publishing.value = false; // 确保按钮状态正确重置
    
    // 2秒后跳转到我的发布页面，添加时间戳确保列表刷新
    setTimeout(() => {
      router.push({
        path: '/shop/my-items',
        query: { updated: Date.now() }
      });
    }, 2000);
  } catch (error: any) {
    console.error('操作商品失败:', error);
    message.value = error.message || '操作失败，请稍后重试';
    messageType.value = 'error';
    publishing.value = false;
  }
};

// 组件挂载时检查是否为编辑模式
onMounted(() => {
  // 检查是否有编辑模式的参数
  const idParam = route.query.id;
  if (idParam) {
    isEditMode.value = true;
    itemId.value = Number(idParam);
    if (!isNaN(itemId.value)) {
      loadItemDetail(itemId.value);
    }
  }
});

// 组件卸载时清理定时器
onUnmounted(() => {
  if (messageTimeout) {
    clearTimeout(messageTimeout);
  }
});
</script>

<style scoped>
.publish-item-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.publish-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 40px;
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 40px;
  font-size: 28px;
}

.publish-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 表单组 */
.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  position: relative;
}

.form-label {
  font-weight: 600;
  color: #333;
  font-size: 15px;
}

.required {
  color: #ff4d4f;
  margin-left: 4px;
}

.form-input,
.form-textarea,
.form-select {
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 15px;
  transition: border-color 0.3s;
  font-family: inherit;
}

.form-input:focus,
.form-textarea:focus,
.form-select:focus {
  outline: none;
  border-color: #52C41A;
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.char-count {
  align-self: flex-end;
  font-size: 12px;
  color: #999;
  margin-top: -4px;
}

/* 价格输入 */
.price-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.price-symbol {
  position: absolute;
  left: 16px;
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}

.price-input {
  padding-left: 36px;
}

/* 图片上传区域 */
.image-upload-group {
  margin-bottom: 10px;
}

.image-upload-area {
  width: 100%;
}

.upload-placeholder {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}

.upload-placeholder:hover {
  border-color: #52C41A;
  background-color: #f6ffed;
}

.upload-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.upload-placeholder p {
  margin: 8px 0;
  color: #666;
  font-size: 15px;
}

.upload-hint {
  font-size: 13px;
  color: #999;
}

.image-preview-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
}

.image-preview {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
  display: block;
  border-radius: 8px;
  border: 2px solid #e0e0e0;
}

.image-actions {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

.change-image-btn,
.remove-image-btn {
  flex: 1;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.change-image-btn {
  background-color: #1890ff;
  color: white;
}

.change-image-btn:hover {
  background-color: #096dd9;
  transform: translateY(-2px);
}

.remove-image-btn {
  background-color: #ff4d4f;
  color: white;
}

.remove-image-btn:hover {
  background-color: #cf1322;
  transform: translateY(-2px);
}

.upload-progress {
  margin-top: 8px;
  font-size: 14px;
  color: #52C41A;
  font-weight: 500;
}

/* 按钮组 */
.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.publish-btn,
.reset-btn {
  flex: 1;
  padding: 14px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.publish-btn {
  background: linear-gradient(135deg, #52C41A 0%, #389e0d 100%);
  color: white;
}

.publish-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

.publish-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.reset-btn:hover:not(:disabled) {
  background-color: #e8e8e8;
}

.reset-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 消息提示 */
.message {
  margin-top: 10px;
  padding: 12px 16px;
  border-radius: 8px;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
}

.message.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.message.error {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

/* 响应式 */
@media (max-width: 768px) {
  .publish-container {
    padding: 20px;
  }
  
  .page-title {
    font-size: 24px;
    margin-bottom: 30px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .upload-placeholder {
    padding: 40px 20px;
  }
  
  .upload-icon {
    font-size: 48px;
  }
}
</style>
